"""
Send the information of a game controller on the can bus.

This tool needs pygame and python-can
- https://www.pygame.org/news
- https://python-can.readthedocs.io/en/master/

Please install pygame by:
   py -m pip install -U pygame --user 

Please install python-can by:
    pip install python-can

"""


import pygame
import can
import stdtype

can_id=0x7c0

sim_can = can.interface.Bus(bustype='vector', app_name='canstick', channel=0,bitrate=500000)

pygame.init()

pygame.display.set_caption("canstick")

# Loop until the user clicks the close button.
done = False

# Used to manage fast the main loop is running 
clock = pygame.time.Clock()

# Initialize the joysticks.
pygame.joystick.init()

# create joystick
joystick = pygame.joystick.Joystick(0)

# initialize joystick
joystick.init()


delay_counter=0

# store da anlalog value of the axes
axes=4*[0]

# store the bool information of the buttons
buttons=16*[0]

msg_data_last=8*[0x00]
# -------- Main Program Loop -----------
while not done:  

    for event in pygame.event.get(): # User did something.
        if event.type == pygame.QUIT: # If user clicked close.
            done = True # Flag that we are done so we exit this loop.

    msg_data=8*[0] #clear msg
    
    # read buttons
    for i in range(12):
        value=joystick.get_button(i)
        msg_data[i>>3]|=value<<(i&0x07)
 
    # read head which has another 4 buttons
    hat = joystick.get_hat(0)
    h=[hat[0]>0,hat[0]<0,hat[1]>0,hat[1]<0]
    for i in range(len(h)):
        msg_data[(i+12)>>3]|=h[i]<<((i+12)&0x07)

    # read axes
    for i in range(4):
        value=stdtype.S8(round(joystick.get_axis(i)*100)) # scale to +-100%
        msg_data[4+i]=value.get_as_list()[0]
        

    if msg_data!=msg_data_last:
          msg_data_last=msg_data
          delay_counter=0 # allow sending of data in this cycle
          
    if delay_counter:
        delay_counter-=1
    else:
        #send data
        delay_counter=99 # reload timer to 1000ms
        print( msg_data)
        msg = can.Message(arbitration_id=can_id,data=msg_data,extended_id=False)
        sim_can.send(msg)

    clock.tick(100) # 100 updates per second equals 10ms
      
pygame.quit()
